package gncom.qr;

import java.text.SimpleDateFormat;
import java.util.Vector;

import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class StoryDeletePage extends ListActivity {

	private Vector<StoryVO> list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.story_delete_page);

		if (getIntent().getStringExtra("url") != null) {
			saveURL(getIntent().getStringExtra("url"));
			list = getStoryInfoList();
		}

		list = getStoryInfoList();

		setListAdapter(new SpeechListAdapter(this, list));

		Button storyEditBtn = (Button) findViewById(R.id.storyEditBtn);

		storyEditBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(getApplicationContext(), StoryPage.class));
			}
		});
	}

	private Vector<StoryVO> getStoryInfoList() {
		openData();
		Cursor c = mDatabase.query("qrStory", null, null, null, null, null, "id desc");

		if (c.getCount() == 0) {
			Toast.makeText(this, "저장된 내용이 없습니다.\n 스캔 후 저장 하세요.", 0).show();
		}
		Vector<StoryVO> list = new Vector<StoryVO>();
		StoryVO vo = null;
		c.moveToFirst();
		while (!(c.isAfterLast())) {
			vo = new StoryVO();
			vo.setId(c.getInt(c.getColumnIndex("id")));
			vo.setUrl(c.getString(c.getColumnIndex("url")));
			vo.setCdate(c.getLong(c.getColumnIndex("cdate")));
			vo.setStory(c.getString(c.getColumnIndex("story")));
			list.add(vo);
			c.moveToNext();
		}
		return list;
	}

	private void saveURL(String url) {
		// 1.DB 연결.
		openData();

		// 2.입력.
		ContentValues values = new ContentValues();
		values.put("url", url);
		values.put("cdate", System.currentTimeMillis());

		long result = mDatabase.insert("qrStory", null, values);
		Log.i("qr", result + ".....");

		// 3.서버로 입력.
		// 아직 미구현...
	}

	private SQLiteDatabase mDatabase;

	private void openData() {
		mDatabase = openOrCreateDatabase("storyInfo", SQLiteDatabase.CREATE_IF_NECESSARY, null);
		Cursor c = mDatabase.rawQuery("select name from sqlite_master where type=? and name=?", new String[] { "table", "qrStory" });
		if (c.getCount() == 0) {
			mDatabase.execSQL("create table qrStory(id integer primary key autoincrement,url text,cdate long,story text);");
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		((SpeechListAdapter) getListAdapter()).toggle(position);
	}

	private String[] mTitles = null;
	private String[] mDialogue = null;
	private int[] mID = null;

	private class SpeechListAdapter extends BaseAdapter {
		public SpeechListAdapter(Context context, Vector<StoryVO> list) {
			mContext = context;
			mID = new int[list.size()];
			mTitles = new String[list.size()];
			mDialogue = new String[list.size()];
			setStringArray(list);
		}

		private void setStringArray(Vector<StoryVO> list) {
			for (int i = 0; i < list.size(); i++) {
				StoryVO x = list.get(i);
				mID[i] = x.getId();
				mTitles[i] = x.getUrl() + "\n" + setDateFormat(x.getCdate());
				mDialogue[i] = x.getStory();
				mExpanded[i] = false;
			}
		}

		private String setDateFormat(long cdate) {
			String textDate = "";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			textDate = sdf.format(cdate);
			return textDate;
		}

		public int getCount() {
			return mTitles.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			SpeechView sv;
			if (convertView == null) {
				sv = new SpeechView(mContext, mTitles[position], mDialogue[position], mExpanded[position]);
			} else {
				sv = (SpeechView) convertView;
				sv.setTitle(mTitles[position]);
				sv.setDialogue(mDialogue[position]);
				sv.setExpanded(mExpanded[position]);
			}
			return sv;
		}

		public void toggle(int position) {
			mExpanded[position] = !mExpanded[position];

			Log.i("qr", "onListItemClick.......mExpanded..." + mExpanded[position]);
			Log.i("qr", "onListItemClick.......mID..." + mID[position]);

			// 1. 펼쳐질때만 글쓰기 화면으로 이동시키기.mExpanded[position]>>>true 일때.
			// 2. 글쓴 내용이 있는지 없는지 비교해서 없을때만 글쓰기 화면으로 이동시키기.isStory>>true일때
			boolean isStory = haveAStory(mID[position]);

			// 3. 1.2번 동시만족일때만 글쓰기로 이동.
			if (mExpanded[position] && isStory) {
				startActivity(new Intent(getApplicationContext(), StoryWritePage.class).putExtra("id", mID[position]));
			}
			notifyDataSetChanged();
		}

		private boolean haveAStory(int id) {
			Cursor c = mDatabase.query("qrStory", null, "id=?", new String[] { id + "" }, null, null, null);
			c.moveToFirst();
			String story = c.getString(c.getColumnIndex("story"));
			boolean isStory = false;
			Log.i("qr", "onListItemClick...." + id + "......" + story);
			if (story == null) {
				isStory = true;
			}
			return isStory;
		}

		private Context mContext;

		// private String[] mTitles = { "http://m.naver.com \n2011.10.01 10:30",
		// "http://m.naver.com \n2011.10.01 10:30",
		// "http://m.naver.com \n2011.10.01 10:30",
		// "http://m.naver.com \n2011.10.01 10:30",
		// "http://m.naver.com \n2011.10.01 10:30",
		// "http://m.naver.com \n2011.10.01 10:30",
		// "http://m.naver.com \n2011.10.01 10:30",
		// "http://m.naver.com \n2011.10.01 10:30" };
		// private String[] mDialogue = {
		// "http://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \n ",
		// "http://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \n ",
		// "http://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \n ",
		// "http://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \n ",
		// "http://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \n ",
		// "http://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \n ",
		// "http://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \n ",
		// "http://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \nhttp://m.naver.com 2011.10.01 10:30 \n ",
		// };

		private boolean[] mExpanded = { false, false, false, false, false, false, false, false };
	}

	private class SpeechView extends LinearLayout {
		private int[] mArrows = { R.drawable.qr_box, R.drawable.qr_box2 };

		public SpeechView(Context context, String title, String dialogue, boolean expanded) {
			super(context);

			this.setOrientation(VERTICAL);
			// this.setBackgroundResource(R.drawable.notice_bg);
			this.setBackgroundColor(Color.rgb(30, 30, 30));

			LinearLayout top = new LinearLayout(context);
			top.setOrientation(HORIZONTAL);
			top.setBackgroundResource(R.drawable.story_info_box);

			LinearLayout lin01 = new LinearLayout(context);
			lin01.setOrientation(HORIZONTAL);
			lin01.setBackgroundResource(R.drawable.story_info_box);
			lin01.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			mArrow = new ImageView(context);
			mArrow.setImageResource(mArrows[0]);

			lin01.addView(mArrow);

			mTitle = new TextView(context);
			mTitle.setPadding(10, 15, 15, 0);
			mTitle.setTextColor(Color.WHITE);
			mTitle.setTextSize(16);
			mTitle.setText(title);

			lin01.addView(mTitle);

			CheckBox mCheck = new CheckBox(context);
			mCheck.setText("");

			lin01.addView(mCheck);

			addView(lin01);

			mDialogue = new TextView(context);
			mDialogue.setPadding(30, 15, 0, 15);
			mDialogue.setTextSize(15);
			mDialogue.setText(dialogue);
			mDialogue.setTextColor(Color.WHITE);
			addView(mDialogue, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

			mDialogue.setVisibility(expanded ? VISIBLE : GONE);
		}

		public void setTitle(String title) {
			mTitle.setText(title);
		}

		public void setDialogue(String words) {
			mDialogue.setText(words);
		}

		public void setExpanded(boolean expanded) {
			mDialogue.setVisibility(expanded ? VISIBLE : GONE);
			mArrow.setImageResource(expanded ? mArrows[1] : mArrows[0]);
		}

		private ImageView mArrow;
		private TextView mTitle;
		private TextView mDialogue;
	}
}